const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 获取用户购物车
  async getCartByUserId(userId) {
    const [cartItems] = await db.execute(
      'SELECT ci.*, p.name, p.price, p.images FROM cart_items ci ' +
      'JOIN products p ON ci.product_id = p.id ' +
      'WHERE ci.user_id = ? AND p.status = "active"',
      [userId]
    );
    return cartItems;
  },

  // 添加商品到购物车
  async addToCart(userId, productId, quantity = 1) {
    // 检查商品是否存在且可用
    const [products] = await db.execute(
      'SELECT id, stock FROM products WHERE id = ? AND status = "active"',
      [productId]
    );
    
    if (products.length === 0) {
      throw new Error('商品不存在或已下架');
    }
    
    const product = products[0];
    
    // 检查库存
    if (product.stock < quantity) {
      throw new Error('库存不足');
    }
    
    // 检查是否已在购物车
    const [existingItems] = await db.execute(
      'SELECT * FROM cart_items WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    if (existingItems.length > 0) {
      // 更新数量
      const newQuantity = existingItems[0].quantity + quantity;
      if (newQuantity > product.stock) {
        throw new Error('超过库存数量');
      }
      
      const [result] = await db.execute(
        'UPDATE cart_items SET quantity = ? WHERE id = ?',
        [newQuantity, existingItems[0].id]
      );
      return result.affectedRows > 0;
    } else {
      // 新增记录
      const [result] = await db.execute(
        'INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)',
        [userId, productId, quantity]
      );
      return result.affectedRows > 0;
    }
  },

  // 更新购物车商品数量
  async updateCartItem(userId, itemId, quantity) {
    // 获取当前购物车项
    const [items] = await db.execute(
      'SELECT ci.*, p.stock FROM cart_items ci ' +
      'JOIN products p ON ci.product_id = p.id ' +
      'WHERE ci.id = ? AND ci.user_id = ?',
      [itemId, userId]
    );
    
    if (items.length === 0) {
      throw new Error('购物车项不存在');
    }
    
    const item = items[0];
    
    // 检查库存
    if (quantity > item.stock) {
      throw new Error('库存不足');
    }
    
    // 更新数量
    const [result] = await db.execute(
      'UPDATE cart_items SET quantity = ? WHERE id = ? AND user_id = ?',
      [quantity, itemId, userId]
    );
    
    return result.affectedRows > 0;
  },

  // 从购物车移除商品
  async removeFromCart(userId, itemId) {
    const [result] = await db.execute(
      'DELETE FROM cart_items WHERE id = ? AND user_id = ?',
      [itemId, userId]
    );
    return result.affectedRows > 0;
  },

  // 清空购物车
  async clearCart(userId) {
    const [result] = await db.execute(
      'DELETE FROM cart_items WHERE user_id = ?',
      [userId]
    );
    return result.affectedRows > 0;
  }
};